package com.cyclecoder.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * @author by zhanglei
 * @Date 2021/8/16
 */
public class SendMessage {
    private final static String QUEUENAME = "rabbitmq_test";

    public static void main(String[] args) throws IOException, TimeoutException {
//        producerMessage("nihao");
        consumerMessage();
    }

    private static void producerMessage(String message) {
        Connection connection = null;
        Channel channel = null;
        try {
            connection = RabbitmqUtil.getConnection();
            channel = connection.createChannel();
            channel.queueDeclare(QUEUENAME, false, false, false, null);
            channel.basicPublish("", QUEUENAME, null, message.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {

            try {
                if (channel != null) {
                    channel.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }
    }

    private static void consumerMessage() {
        Connection connection = null;
        Channel channel = null;
        try {
            connection = RabbitmqUtil.getConnection();
            channel = connection.createChannel();
            channel.basicConsume(QUEUENAME, true, new MyComsumer(channel));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {

            try {
                if (channel != null) {
                    channel.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }
    }
}
